﻿var html = "PanicBuying/TicketPanicBuying.html";
var daojs = "";
var jsdaojs = "";
var token = "1";
var guid = ""; 
var canSubmit = true;
var TotalNumber = 0;
//iss_localStorage.set("yuqing_appAccount", "b760689cb63a4a92834d6f14173bc293")
//iss_localStorage.set("yuqing_appOpenId", "oX816v6aIyS0-INie0Ee9N_jhIY0")

var contactsCallback_PanicBuying = myApp.onPageInit('Questionnaire', function (page) {

    //非微信浏览器下  不显示标题
    // if (!ISS.utils.isWeiXin()) {
    //     mainView.hideNavbar();
    //     $$('.page-content').attr('style', 'margin-top:-44px')
    // }

    //获取页面参数
    var userID = ISS.utils.getParameter("userID");
    if (userID && userID != undefined && userID != null && userID != "") {
        iss_localStorage.set("yuqing_appUserId", userID);
        mainView.hideNavbar();
        $$('.page-content').css('style', 'margin-top:-44px')
    }

    var _content = JSON.stringify(
        {
            AccountGuid: iss_localStorage.get("yuqing_appAccount"),
            OpenId: iss_localStorage.get("yuqing_appOpenId")
            // OpenId:"oX816v34ifGyjDa9nqWIS4AVniWo"
        });

    InitPanicBuying(_content);
})

function InitPanicBuying(content) {

    $$.ajax({
        url: ISS_Constants.Url.const_weixin_TickePanicBuying_get,
        data: { conditionParm: content },
        crossDomain: true,
        dataType: "json",
        success: function (data, status) {

            if (data.datas) {
                data.datas.begindate = ISS.utils.dateToStr("yyyy-MM-dd", ISS.utils.strToDate(data.datas.PanicBuyingBeginTime)); // ISS.utils.dateToStr("yyyy-MM-dd", new Date());
                data.datas.begintime = ISS.utils.dateToStr("HH:mm", ISS.utils.strToDate(data.datas.PanicBuyingBeginTime)); // ISS.utils.dateToStr("HH:mm:ss", new Date(ISS.utils.ReplaceHMS(data.datas.PanicBuyingBeginTime)));
                daojs = ISS.utils.strToDate(data.datas.PanicBuyingBeginTime)
                jsdaojs = ISS.utils.strToDate(data.datas.PanicBuyingEndTime)
                guid = data.datas.PanicBuyingActiveGuid;
                TotalNumber = data.datas.PanicBuyingProductNum;
                var searchTemplate = $$('#template-ticketpanicbuying-info').html();
                if (searchTemplate) {
                    var compiledTemplate = Template7.compile(searchTemplate);
                    var html = compiledTemplate(data.datas);
                    $$(".page-content").html('')
                    $$(".page-content").html(html);

                    $$(".act_tickets .qg_img_box a img").attr("src", _HttpDomain + data.datas.PanicBuyingActiveImgUrl);
                    show_time(daojs);
                    if ($$('#djsr').html() == "00" && $$('#djss').html() == "00" && $$('#djsf').html() == "00") {
                        $$('.clearfix p').html($$('.clearfix p').html().replace('共计', '剩余'))
                        $$('.clearfix li').eq(0).html('据结束:')
                        show_time(jsdaojs);
                    }

                    getPepol(guid);
                }

            } else {
                $$('.page-content').attr('style', 'display:none');
                $$('#zw').attr('style', 'display:block');
            }


        },
        error: function (xhr, status) { }


    });
}

function getPepol(guid) {
    $$.ajax({
        url: ISS_Constants.Url.const_weixin_TickePanicBuying_player_get,
        data: {
            conditionParm: JSON.stringify(
                {
                    AccountGuid: iss_localStorage.get("yuqing_appAccount"),
                    PanicBuyingActiveGuid: guid
                })
        },
        crossDomain: true,
        dataType: "json",
        success: function (data, status) {
            if (data.datas) {
                var html = "";
                for (var i = 0; i < data.datas.length; i++) {
                    if (data.datas[i].NickName == null || data.datas[i].NickName == "" || data.datas[i].NickName == "null") {
                        data.datas[i].NickName = "佚名";
                    }
                    html = "<li>" +
                        "<div class='qglist_img'>" +
                        "<img src='" + data.datas[i].HeadImgUrl + "'>" +
                        "</div>" +
                        "<p>" +
                        data.datas[i].NickName + "<span>" + data.datas[i].Province + " " + data.datas[i].City + "</span></p>" +
                        "</li>";
                    $$('#userlist').append(html)
                }
                for(var i=0;i<data.datas.length; i++){
                    if(data.datas[i].OpenId==iss_localStorage.get("yuqing_appOpenId")){
                        $$('.kq_btn').html("已抢购");
                        return;
                    }
                }
                $$('.kq_btn').on('click', 'a', function () {
                    if ($$(".qg_img_box span").html() == "0张") {
                        myApp.alert('已经没有商品可供抢购')
                        return;
                    }
                    CheckPopLogin(function () {
                        if (canSubmit) {
                            if ($$('.clearfix li').eq(0).html() == "据结束:") {
                                updateTimeLabel(15);
                                panicbuying();
                            } else {
                                myApp.alert("请耐心等待，抢购即将开始");

                            }
                        }
                    })
                })
                //$$('#userlist').html(html);
            }
        },
        error: function (xhr, status) { }
    });
}

//支付
function panicbuying() {
    var content = JSON.stringify(
        {
            AccountGuid: iss_localStorage.get("yuqing_appAccount"),
            OpenId: iss_localStorage.get("yuqing_appOpenId"),
            // OpenId:"oX816v34ifGyjDa9nqWIS4AVniWo",
            Token: token,
            PanicBuyingActiveGuid: guid,
            UserPhone: iss_localStorage.get("yuqing_appPhone")
        });

    $$.ajax({
        url: ISS_Constants.Url.const_weixin_TickePanicBuying_player_save,
        data: { conditionParm: content },
        crossDomain: true,
        dataType: "json",
        success: function (data, status) {
            if (data.datas) {
                --TotalNumber;
                $$('.clearfix p span').html(TotalNumber + "张");
                if (data.msg != "" && data.msg != "2") {
                    //订单号 类型：平台，自运营 回调函数
                    WxPay.utils.UnifiedoOrder(data.msg, '2', function (result) {
                        mainView.router.loadPage({ url: "../booking/payResult.html?result=" + result + "&type=1", reload: false })
                    });
                } else if (data.msg != "" && data.msg == "2") {
                    myApp.alert("抢购成功");
                }
            } else {
                myApp.alert(data.msg);
            }

        },
        error: function (xhr, status) {
            debugger;
        }
    });


}

//倒计时
function show_time(time) {
    var time_start = new Date().getTime(); //设定当前时间
    var time_end = new Date(time).getTime(); //设定目标时间
    if (time_start < time_end) {
        // 计算时间差 

        var time_distance = time_end - time_start;
        // 天
        var int_day = Math.floor(time_distance / 86400000)
        time_distance -= int_day * 86400000;
        // 时
        var int_hour = Math.floor(time_distance / 3600000)
        time_distance -= int_hour * 3600000;
        // 分
        var int_minute = Math.floor(time_distance / 60000)
        time_distance -= int_minute * 60000;
        // 秒 
        var int_second = Math.floor(time_distance / 1000)
        // 时分秒为单数时、前面加零 
        if (int_day < 10) {
            int_day = "0" + int_day;
        }
        if (int_hour < 10) {
            int_hour = "0" + int_hour;
        }
        if (int_minute < 10) {
            int_minute = "0" + int_minute;
        }
        if (int_second < 10) {
            int_second = "0" + int_second;
        }
        // 显示时间 
        $$("#djsr").html(int_day);
        $$("#djss").html(int_hour);
        $$("#djsf").html(int_minute);
        $$("#djsm").html(int_second);
        // 设置定时器
        setTimeout("show_time('" + time + "')", 1000);
    } else {
        $$("#djsr").html('00');
        $$("#djss").html('00');
        $$("#djsf").html('00');
        $$("#djsm").html(int_second);
        $$(".kq_btn").html('立即开抢<span>&gt;</span>')
    }
}

//倒计时
function updateTimeLabel(time) {
    var btn = $$(".kq_btn");
    // btn.fadeIn(1000);
    btn.html(time <= 0 ? "立即开抢<span>&gt;</span>" : ("" + (time) + "秒后可抢购"));
    var hander = setInterval(function () {
        if (time <= 0) {
            canSubmit = true;
            clearInterval(hander)
            btn.html("立即开抢<span>&gt;</span>");
            btn.css({ "cursor": "hand" }); //.attr("disabled",false);  

        }
        else {
            canSubmit = false;
            btn.html("" + (time--) + "秒后可抢购");
        }
    }, 1000);
}


function initData() {
    var href = window.location.href;
    if (href.indexOf(html) > -1) {
        contactsCallback_PanicBuying.trigger();
    }
}

initData();